<template>
  <view class="container">
    <view class="form-item">
      <text class="label">任务名称</text>
      <input v-model="form.taskName" disabled placeholder="任务名称" />
    </view>

    <view class="form-item">
      <text class="label">完成说明</text>
      <textarea v-model="form.completionNotes" placeholder="请输入任务完成说明" rows="4" />
    </view>

    <view class="form-item">
      <text class="label">完成状态</text>
      <picker @change="bindPickerChange" :value="statusIndex" :range="statusArray">
        <view class="picker">{{statusArray[statusIndex]}}</view>
      </picker>
    </view>

    <view class="form-item">
      <button type="primary" @click="submitForm">提交完成</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        taskId: '',
        taskName: '',
        completionNotes: '',
        completionStatus: '无故障',
        completedByUsername: uni.getStorageSync('username') || ''
      },
      statusArray: ['无故障', '有小问题', '有严重问题'],
      statusIndex: 0
    };
  },
  // 在 WorkPages 页面的 script 部分
  onShow() {
    // 每次页面显示时都刷新任务列表
    this.getTaskList();
  },
  onLoad(options) {
    if (options.task) {
      const task = JSON.parse(decodeURIComponent(options.task));
      this.form.taskId = task.taskId;
      this.form.taskName = task.taskName;
    }
  },
  methods: {
    bindPickerChange(e) {
      this.statusIndex = e.detail.value;
      this.form.completionStatus = this.statusArray[this.statusIndex];
    },
    submitForm() {
      if (!this.form.completionNotes) {
        uni.showToast({ title: '请填写完成说明', icon: 'none' });
        return;
      }

      const token = uni.getStorageSync('token');
      uni.request({
        url: this.$baseUrl + '/work/completeTask',
        method: 'POST',
        header: {
          'satoken': token,
          'Content-Type': 'application/json'
        },
        data: this.form,
        success: (res) => {
          if (res.data.code === 200) {
            uni.showToast({ title: '任务完成提交成功', icon: 'success' });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({ title: res.data.message || '提交失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络请求失败', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 30rpx;
}
.form-item {
  margin-bottom: 30rpx;
}
.label {
  display: block;
  margin-bottom: 10rpx;
  font-size: 28rpx;
  color: #333;
}
input,
textarea {
  width: 100%;
  padding: 20rpx;  
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  font-size: 28rpx;
  background-color: #fff;
  box-sizing: border-box;
  min-height: 80rpx;
}
textarea {
  height: 200rpx;
  resize: none;
  overflow-y: auto;
}
.picker {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  font-size: 28rpx;
  background-color: #fff;
  box-sizing: border-box;
}
</style>